import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径，使Core模块可导入
current_dir = Path(__file__).parent
project_root = current_dir.parent  # 获取App的父目录（项目根目录）
sys.path.append(str(project_root))

from PySide6.QtWidgets import (QApplication, QMainWindow, QComboBox, 
                             QVBoxLayout, QWidget, QLabel, QPushButton,
                             QTextEdit, QHBoxLayout, QLineEdit)
from PySide6.QtCore import Qt
from Core.blutooth import BluetoothManager, BluetoothDevice
from Core.timer import RepeatingTimer  # 从Core导入定时器模块

class BluetoothApp(QMainWindow):
    """蓝牙设备管理应用主窗口"""
    def __init__(self):
        super().__init__()
        
        self.bluetooth_manager = BluetoothManager()  # 确保这行代码没有错误
        
        # 初始化UI界面
        self.init_ui()
        
        # 初始化蓝牙管理器
        self.bluetooth_manager = BluetoothManager()
        self.setup_bluetooth_signals()
        
        # 初始化定时器，每秒扫描一次设备
        self.init_timer()
        
        # 存储设备列表
        self.device_list = []
    
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("BLE设备管理器")
        self.setGeometry(100, 100, 600, 500)
        
        # 创建中心部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 设备选择区域
        device_group = QVBoxLayout()
        device_group.addWidget(QLabel("<b>蓝牙设备列表</b>"))
        
        self.device_combo = QComboBox()
        self.device_combo.setMinimumHeight(35)
        self.device_combo.setPlaceholderText("扫描中，请稍候...")
        device_group.addWidget(self.device_combo)
        
        # 设备操作按钮
        btn_layout = QHBoxLayout()
        self.connect_btn = QPushButton("连接设备")
        self.connect_btn.setMinimumHeight(30)
        self.connect_btn.setEnabled(False)
        
        self.disconnect_btn = QPushButton("断开连接")
        self.disconnect_btn.setMinimumHeight(30)
        self.disconnect_btn.setEnabled(False)
        
        self.refresh_btn = QPushButton("手动刷新")
        self.refresh_btn.setMinimumHeight(30)
        
        btn_layout.addWidget(self.connect_btn)
        btn_layout.addWidget(self.disconnect_btn)
        btn_layout.addWidget(self.refresh_btn)
        device_group.addLayout(btn_layout)
        
        main_layout.addLayout(device_group)
        
        # 数据发送区域
        send_group = QVBoxLayout()
        send_group.addWidget(QLabel("<b>发送数据</b>"))
        
        self.data_input = QLineEdit()
        self.data_input.setMinimumHeight(35)
        self.data_input.setPlaceholderText("输入要发送的数据...")
        send_group.addWidget(self.data_input)
        
        self.send_btn = QPushButton("发送数据")
        self.send_btn.setMinimumHeight(30)
        self.send_btn.setEnabled(False)
        send_group.addWidget(self.send_btn)
        
        main_layout.addLayout(send_group)
        
        # 接收数据区域
        recv_group = QVBoxLayout()
        recv_group.addWidget(QLabel("<b>接收数据</b>"))
        
        self.recv_display = QTextEdit()
        self.recv_display.setMinimumHeight(100)
        self.recv_display.setReadOnly(True)
        recv_group.addWidget(self.recv_display)
        
        main_layout.addLayout(recv_group)
        
        # 状态显示区域
        self.status_label = QLabel("状态：准备就绪")
        self.status_label.setStyleSheet("color: #666; font-style: italic;")
        main_layout.addWidget(self.status_label)
        
        # 连接按钮信号
        self.connect_btn.clicked.connect(self.connect_selected_device)
        self.disconnect_btn.clicked.connect(self.bluetooth_manager.disconnect_device)
        self.refresh_btn.clicked.connect(self.bluetooth_manager.start_scan)
        self.send_btn.clicked.connect(self.send_data)
    
    def setup_bluetooth_signals(self):
        """设置蓝牙管理器的信号连接"""
        # 设备列表更新
        self.bluetooth_manager.devices_updated.connect(self.update_device_list)
        # 状态更新
        self.bluetooth_manager.status_updated.connect(self.update_status)
        # 错误信息
        self.bluetooth_manager.error_occurred.connect(self.show_error)
        # 接收数据
        self.bluetooth_manager.data_received.connect(self.display_received_data)
    
    def init_timer(self):
        """初始化定时器"""
        self.timer = RepeatingTimer(interval_ms=1000)  # 1秒间隔
        self.timer.timeout.connect(self.bluetooth_manager.start_scan)
        self.timer.start()
    
    def update_device_list(self, devices):
        """更新设备下拉列表"""
        self.device_list = devices
        self.device_combo.clear()
        
        if not devices:
            self.device_combo.addItem("未发现BLE设备")
            self.connect_btn.setEnabled(False)
        else:
            for device in devices:
                self.device_combo.addItem(str(device))
            self.connect_btn.setEnabled(True)
    
    def connect_selected_device(self):
        """连接选中的设备"""
        current_index = self.device_combo.currentIndex()
        if 0 <= current_index < len(self.device_list):
            selected_device = self.device_list[current_index]
            self.bluetooth_manager.connect_device(selected_device)
            self.disconnect_btn.setEnabled(True)
            self.send_btn.setEnabled(True)
    
    def send_data(self):
        """发送数据到已连接设备"""
        text = self.data_input.text().strip()
        if not text:
            self.show_error("请输入要发送的数据")
            return
        
        # 将文本转换为字节数据（根据设备要求调整编码）
        try:
            data = text.encode('utf-8')
            self.bluetooth_manager.send_data(data)
            self.data_input.clear()
        except Exception as e:
            self.show_error(f"数据编码错误: {str(e)}")
    
    def update_status(self, message):
        """更新状态信息"""
        self.status_label.setText(f"状态：{message}")
        
        # 根据状态更新按钮状态
        if "已连接" in message:
            self.connect_btn.setEnabled(False)
            self.disconnect_btn.setEnabled(True)
            self.send_btn.setEnabled(True)
        elif "已断开" in message:
            self.connect_btn.setEnabled(True if self.device_list else False)
            self.disconnect_btn.setEnabled(False)
            self.send_btn.setEnabled(False)
    
    def show_error(self, error_message):
        """显示错误信息"""
        self.status_label.setText(f"错误：{error_message}")
        self.status_label.setStyleSheet("color: #ff0000; font-style: italic;")
    
    def display_received_data(self, data):
        """显示接收的数据"""
        try:
            # 尝试将字节数据转换为字符串
            text = data.decode('utf-8')
            self.recv_display.append(f"收到: {text}")
        except UnicodeDecodeError:
            # 无法解码时显示原始字节
            self.recv_display.append(f"收到数据: {data.hex()}")
    
    def closeEvent(self, event):
        """窗口关闭时清理资源"""
        self.timer.stop()
        self.bluetooth_manager.disconnect_device()
        event.accept()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = BluetoothApp()
    window.show()
    sys.exit(app.exec())
    